package com.demo.common;

import com.demo.Yaml;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @author root
 * @description TODO
 * @date 2020/12/3 11:42
 */
public final class JedisConfig {
    /** 连接超时时间 **/
    public static int connectionTimeout = 2000;
    /** 读取数据超时时间 **/
    public static int soTimeout = 2000;
    /** 连接重试最大次数 **/
    public static int maxAttempts = 5;
    /** 连接名 **/
    public static String clientName = "jedisCluster";

    /**
     * @author lc
     * @date 2020/12/3
     * @description redis集群构建
     */
    public static JedisCluster getJedisCluster(Yaml yaml) {
        Set<HostAndPort> nodesSets = new HashSet<>();
        String[] strNode = yaml.getNodes().split(",");
        for (String redisNode : strNode) {
            String host = redisNode.split(":")[0];
            int port = Integer.parseInt(redisNode.split(":")[1]);
            HostAndPort hostAndPort = new HostAndPort(host, port);
            nodesSets.add(hostAndPort);
        }
        JedisCluster jedisCluster = new JedisCluster(nodesSets);
        if (yaml.getUser() != null && yaml.getPassword() != null) {
            jedisCluster = new JedisCluster(nodesSets,connectionTimeout,soTimeout,maxAttempts,yaml.getUser(),yaml.getPassword(),clientName,new JedisPoolConfig());
        } else if (yaml.getPassword() != null) {
            jedisCluster = new JedisCluster(nodesSets,connectionTimeout,soTimeout,maxAttempts,yaml.getPassword(),new JedisPoolConfig());
        }
        return jedisCluster;
    }

    /**
     * @author lc
     * @date 2020/12/3
     * @description 单机构造
     */
    public static Jedis getJedis(Yaml yaml) {
        Jedis jedis = new Jedis(yaml.getHost(), yaml.getPort());
        if (yaml.getUser() != null && yaml.getPassword() != null) {
            jedis.auth(yaml.getUser(), yaml.getPassword());
        } else if (yaml.getPassword() != null) {
            jedis.auth(yaml.getPassword());
        }
        return jedis;
    }
}
